<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Description of MY_Controller
 *
 * @author Admin
 */
class MY_Controller extends CI_Controller {

    // Mang truyen bien sang view
    protected $data;
    // Load config tu csdl
    protected $siteConfig;
    // Style hien tai cua trang
    protected $style;
    // Ngon ngu nguoi dung stdClass
    protected $user_lang;
    // Tat car ngon ngu cua trang stdClass array
    protected $languages;
    // Lay location luu o client
    protected $location;
    // Thong tin user hien tai
    protected $user = false;
    var $ajax = false;
    private $inAdminFolder = false;

    function __construct() {
        parent::__construct();
        session_start();
        $this->load->helper('language');
        $this->load->helper('debug');
        $this->load->helper('user');
        $this->load->helper('global');
        $this->load->helper('cookie');
        $this->load->helper('style');
        $this->load->driver('cache');
        $this->load->helper('date');

        $admin_folder = $this->config->item('admin_folder');

        //Detect ajax request
        $header = $this->input->request_headers();
        if (isset($header['Accept'])) {
            $accept = $header['Accept'];
            if (strpos($accept, 'application/json') !== false)
                $this->ajax = true;
        }

        //Load config
        $this->siteConfig = uconfig_get();
        $this->data['config'] = $this->siteConfig;

        //Load style
        $this->style = style_get($this->siteConfig->style);

        // 
        if ($this->session->userdata('user_id') === FALSE)
            $this->session->set_userdata('user_id', $this->siteConfig->guest_id);
        $this->user = $this->getUserInfo();

        //Load config
        $this->siteConfig = uconfig_get();
        $this->data['config'] = $this->siteConfig;

        //Load style
        $this->style = style_get($this->siteConfig->style);

        $this->languages = lang_get_all();
        $this->data['langs'] = $this->languages;

        //Load language
        $this->get_user_lang();
        $this->data['lang'] = $this->user_lang->id;

        if ($this->session->userdata('cart') === FALSE)
            $this->session->set_userdata('cart', array());

        switch ($this->uri->segment(1)) {
            case $admin_folder: {
                    $this->inAdminFolder = true;
                    if ($this->uri->total_segments() == 1)
                        redirect(url_create('admin', 'dashboard'));

                    if ($this->uri->segment(2) != 'login') {
                        if (!$this->isUserLogin()) {
                            redirect($admin_folder . '/login?ref=' . $this->uri->uri_string());
                        }
                        if (!$this->checkPermission()) {
                            if ($this->ajax)
                                echo json_encode(array(
                                    'state' => 'error',
                                    'title' => lang('error'),
                                    'message' => lang('not_authentication'),
                                ));
                            else
                            if ($this->isUserLogin())
                                show_error(lang('not_authentication'));
                            else {
                                redirect(url_create('admin', 'login', 'index') . '?ref=' . urlencode(site_url($this->uri->ruri_string())));
                            }
                        }
                    }
                    $_SESSION['inAdmin'] = true;

                    // Load cac module bang dieu khien
                    $this->load->model('model_module');
                    $modules = $this->model_module->get_list_hash(array(
                        'order' => array('index', 'asc')
                    ));

                    $where = array();
//					if (!$this->isRootAdmin())
                    $where['active'] = true;
                    $menus = $this->model_module->get_list_hash(array(
                        'where' => $where,
                        'order' => array('index', 'asc')
                    ));


                    array_to_object($menus);

                    //Tick module hien tai va cac module cap  tren
                    $curr_controller = $this->uri->segment(2) != '' ? $this->uri->segment(2) : $this->config->item('default_controller');

                    $curr_controller_id = $this->model_module->get_id(array('controller' => $curr_controller));

                    $breadcrumb = breadcrumb_create($modules, $curr_controller_id);

                    $this->data['breadcrumb'] = $breadcrumb;
                    $this->data['active_menu_id'] = $curr_controller_id;
                    $this->data['menus'] = $menus;
                    $this->data['modules'] = $modules;
                    break;
                }
            default: {

                    if ($this->uri->total_segments() == 0)
                        redirect(url_create('site', 'home'));

                    /*if (!$this->checkPermission()) {

                        if ($this->ajax)
                            echo json_encode(array(
                                'state' => 'error',
                                'title' => lang('error'),
                                'message' => lang('not_authentication'),
                            ));
                        else if ($this->isUserLogin())
                            show_error(lang('not_authentication'));
                        else {
                            redirect(url_create('site', 'account', 'fb_login') . '?ref=' . urlencode(site_url($this->uri->uri_string())));
                        }
                    }*/

                    $this->load->model('model_catalogue');

                    if (!$catalogues = $this->cache->file->get('catalogues')) {
                        $catalogues = $this->model_catalogue->get_list_hash($this->siteConfig->lang, array(
                            'where' => array(
                                'active' => 1,
                                'menu' => 1
                            ),
                            'order' => array('index', 'asc')
                        ));
                        array_to_object($catalogues);

                        $this->cache->file->save('catalogues', $catalogues, 5);
                    }

                    $this->data['catalogues'] = $catalogues;
                    $this->data['current_location'] = $this->location;
                    $this->data['is_home'] = false;
//					$this->data['supports'] = array();
                    $this->data['topUsers'] = $this->getTopUsers(12);
                    $this->data['favicon'] = $this->siteConfig->favicon;
                    $this->data['fb_app_id'] = $this->config->item('fb_app_id');
                    $this->data['fb_namespace'] = $this->config->item('fb_namespace');
                    $this->data['social_page'] = $this->siteConfig->social_page;
                    $this->data['meta_desc'] = $this->siteConfig->meta_desc;
                    $this->data['keywords'] = $this->siteConfig->keywords;
                    $this->data['footer'] = $this->siteConfig->footer;
                    $this->data['youtube'] = $this->siteConfig->youtube;
                    $this->data['online_support'] = $this->siteConfig->online_support;
                    $this->data['online_support_desc'] = $this->siteConfig->online_support_desc;
                    $this->data['footer_links'] = $this->siteConfig->footer_links;
                    $this->imageLinkInit();
                    $this->data['news'] = $this->getNews();
                }
        }
        $this->data['isAdmin'] = $this->isAdmin();
//		$this->data['image_src'] = $this->siteConfig->fb_image;
        $this->data['isLogin'] = $this->isUserLogin();
        $this->data['site_title'] = $this->siteConfig->site_title;
        $this->data['user'] = $this->user;
        $this->data['page'] = $this->uri->segment(1) . "." . $this->uri->segment(2);
        $this->data['site_config'] = $this->siteConfig;
        $this->data['url_styles'] = url_styles();

        //
    }

    protected function isRootAdmin() {
        return in_array($this->user->id, $this->config->item('root_admin'));
    }

    protected function isAdmin() {
        return in_array($this->user->group_id, $this->config->item('admin_group')) || $this->isRootAdmin();
    }

    protected function getUserInfo() {
        $this->load->model('model_user');
        $userId = $this->session->userdata('user_id');
        return $this->model_user->get_info($userId);
    }

    protected function isUserLogin() {
        if ($this->user !== false)
            return ($this->user->id !== $this->siteConfig->guest_id);
        return false;
    }

    protected function checkPermission() {
//        pr($this->user);
//        die;
        if ($this->uri->segment(1) == 'cron')
            return true;
        $this->load->model('model_group');

        $group = $this->model_group->get_info($this->user->group_id);

        $permissions = @json_decode($group->permissions);
        if (!$permissions)
            $permissions = array();
        $uri_string = $this->uri->uri_string();
        $segments = 1;
        if ($this->inAdminFolder) {
            $segments = 2;
            $uri_string = preg_replace('/([^\/]+\/[^\/]+\/[^\/]+)(\/.+)?/i', '$1', $uri_string);
        } else {
            $uri_string = preg_replace('/([^\/]+\/[^\/]+)(\/.+)?/i', '$1', $uri_string);
        }
        if ($this->uri->total_segments() == $segments)
            $uri_string .= '/index';
//		echo $uri_string;
//		pr($permissions);
//		die;
//		$this->user->upload_text_image = ($this->isRootAdmin() || $group->upload_text_image == 1) ? TRUE : FALSE;
        return ($this->isRootAdmin() || in_array($uri_string, $permissions));
    }

    protected function load_view() {
        $this->load->view($this->style->folder . '/' . $this->config->item('layout_file'), $this->data);
    }

    private function get_user_location() {
        $location = isset($_COOKIE['location']) ? $_COOKIE['location'] : '';
        if (isset($this->data['locations'][$location]))
            return $location;
        return $this->siteConfig->location;
    }

    private $_topUsers;

    protected function getTopUsers($number) {
        if (!$this->_topUsers) {
            $this->load->model('model_user');
            $this->_topUsers = $this->model_user->get_list(array(
                'where' => array(
                    'active' => 1,
                ),
                'order' => array('access_time', 'desc'),
                'limit' => array(0, $number),
            ));
        }
        return $this->_topUsers;
    }

    /**
     * Upload anh len server
     * @param $image_var
     * @return stdClass
     */
    protected function upload_image($image_var) {
        $config = image_get_upload_config($this->siteConfig);
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload($image_var)) {
            //echo $this->upload->display_errors();
            return false;
        }
        // Upload va resize
        $upload_data = $this->upload->data();
        $resize_config = array(
            'source_image' => $upload_data['full_path'],
            'create_thumb' => TRUE,
            'maintain_ratio' => TRUE,
            'width' => $this->siteConfig->image_width,
            'height' => $this->siteConfig->image_height,
        );
        $this->load->library('image_lib', $resize_config);

        $this->image_lib->resize();
        $this->image_lib->clear();

        $resize_config['image_library'] = 'gd2';
        $resize_config['height'] = $this->siteConfig->thumb_height;
        $resize_config['width'] = $this->siteConfig->thumb_width;
        $resize_config['create_thumb'] = TRUE;
        $this->image_lib->initialize($resize_config);
        $this->image_lib->resize();

        $result = new stdClass();
        $result->path = $config['upload_path'] . '/' . $upload_data['file_name'];
        $result->thumb = preg_replace('/(.+)(\.(' . $this->siteConfig->image_types . '))/i', '$1_thumb$2', $result->path);
        return $result;
    }

    protected function getSlideImages() {
        if (!$slideImages = $this->cache->file->get('slide_images')) {
            $this->load->model('model_image');
            $slideImages = $this->model_image->get_list(array(
                'where' => array('position' => 1)
            ));
            foreach ($slideImages as &$img) {
                $img->image = image_url($img->image);
            }
            $this->cache->file->save('slide_images', $slideImages, 60);
        }
        return $slideImages;
    }

    protected function delImage($path) {
        unlink($path);
    }

    protected function form_is_valid() {
        $this->data['errors'] = array();
        if ($this->form_validation->run())
            return TRUE;
        foreach ($this->form_validation->_field_data as $field => $data) {
            $this->data['errors'][$field] = form_error($field);
        }
        return FALSE;
    }

    private function get_user_lang() {
        $this->load->model('model_lang');
        $id = request('lang');
        $this->user_lang = $this->model_lang->get_info($id);
        if ($this->user_lang === false)
            $this->user_lang = $this->model_lang->get_info($this->siteConfig->lang);
        if ($this->user_lang === false) {
            $languages = $this->model_lang->get_info(array('limit' => array(0, 1)));
            $this->user_lang = $languages[0];
        }
        setcookie('lang', $this->user_lang->id);
    }

    protected function get_new_product($limits) {
        $this->load->model('model_product');
        $products = $this->model_product->get_list(array(
            'where' => array('active' => 1),
            'order' => array('p.id', 'desc'),
            'limit' => array(0, 50),
        ));
        $result_id = array_rand($product, $limits);
        $result = array();
        foreach ($result_id as $id) {
            $result[] = $products[$id];
        }
        return $result;
    }

    private function imageLinkInit() {
        $this->load->model('model_image');
        $images = $this->model_image->get_list();
        $images_link = array();

        foreach ($images as $image) {
            if ($image->target == 1)
                $image->target = ' target="_blank"';
            else
                $image->target = '';
            $images_link[$image->position][] = $image;
        }

        // Logo
        if (isset($images_link[3])) {
            $i = array_rand($images_link[3]);
            $this->data['logo'] = $images_link[3][$i];
        }
        // Banner top
        if (isset($images_link[4])) {
            $i = array_rand($images_link[4]);
            $this->data['banner_top'] = $images_link[4][$i];
        }

        // Banner bottom
        if (isset($images_link[5])) {
//			$i = array_rand($images_link[5]);
            $this->data['banner_bottom'] = $images_link[5];
        }
        // Banner left
        if (isset($images_link[2])) {
            $this->data['banner_left'] = $images_link[2];
        }
        // Slides
        if (isset($images_link[1])) {
            $this->data['slides'] = $images_link[1];
        }
//		pr($this->data['banner_top']);die;
    }

    protected function getNews() {
        $this->load->model('model_page');
        if (!$news = $this->cache->file->get('news')) {
            $news = $this->model_page->get_list(array(
//				'where'	=> array(
//					
//				),
                'order' => array('id', 'desc'),
                'limit' => array(0, 5),
            ));
            $this->cache->file->save('news', $news, 60);
        }
//		$this->data['news'] = $news;
        return $news;
    }

}

?>
